package com.hmy.security.security.service;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import com.hmy.common.exception.Result;
import com.hmy.common.exception.ResultEnum;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 如果接口没有使用{@link com.hmy.security.security.annotation.OpenAccess}标识且用户未登录，
 * 将在此处返回401 - 未认证
 * @see <a href="https://blog.csdn.net/andy_zhang2007/article/details/91355520">AuthenticationEntryPoint简介 - CSDN</a>
 */
@Component
public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        // httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e == null ? "Unauthorized" : e.getMessage());

        // 统一接口返回值
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        httpServletResponse.getWriter().print(JSONObject.toJSONString(Result.error(ResultEnum.UNAUTHORIZED), JSONWriter.Feature.WriteMapNullValue));
    }
}
